import web,sys,os
sys.path.append(os.path.dirname(sys.path[0]))
print sys.path
import simplejson
#sys.path.append('../lcopa')
#from web.template import render
from common import file
from lcopa import calculate_codev,load_uphi_data,lcopa_usb
from tcp_server import tcp_server,udp_server
urls = ("/", "index",
        "/control", "control",
        "/control2", "control2",
        "/upload", "upload_uphi")

app = web.application(urls, globals())
class index:
    def GET(self):
        hello = web.template.frender('./templates/controll.html')
        file_list = ([(name.split('/')[-1]) for name in file.GetFileList('../u-phi')])
        lcopausb = lcopa_usb.LcopaUsb()
        usb_id=lcopausb.get_usb_list()
        #print file_list
        return hello("sss",file_list,usb_id)
class control:
    def GET(self):
        pass
        # hello = web.template.frender('./templates/controll.html')
        # file_list = ([(name.split('/')[-1]) for name in file.GetFileList('../u-phi')])
        # lcopausb = lcopa_usb.LcopaUsb()
        # usb_id=lcopausb.get_usb_list()
        # #print file_list
        # return hello("sss",file_list,usb_id)
    def POST(self):
        data = web.input()
        respon_json={"respone_code":200,"msg":""}
        web.header('content-type','text/json')

        try:
            lcopausb = lcopa_usb.LcopaUsb()
            lcopausb.open(int(data['usb_id'],16))
        except Exception,e:
            print "error",e
            respon_json["msg"] = "usb error"
            respon_json["respone_code"] = 100
            return simplejson.dumps(respon_json)
        try:
            mu_phi = load_uphi_data.u_phi("../u-phi/"+data.file_name)
            # u_phi.load_uphi("../u-phi/"+data.file_name)
        except Exception,e:
            print "error",e
            respon_json["msg"] = "open uphi error"
            respon_json["respone_code"] = 100
            return simplejson.dumps(respon_json)
        print "mu_phi",mu_phi.toString()
        try:
            lcopa = calculate_codev.lcopa_vol(mu_phi)
            btyes = lcopa.calculate_voltage_pi(float(data.angle),float(data.n_pi))
            # print "btyes",btyes
        except Exception,e:
            print "error",e
            respon_json["msg"] = "u-phi file is  error"
            respon_json["respone_code"] = 100
            return simplejson.dumps(respon_json)
        try:
            lcopausb.send_byte(btyes)
        except Exception,e:
            print "error",e
            respon_json["msg"] = "send usb data error"
            respon_json["respone_code"] = 100
            return simplejson.dumps(respon_json)
        #lcopausb.close()
        print "data",data
        return simplejson.dumps(respon_json)

class control2:
    def GET(self):
        pass
        # hello = web.template.frender('./templates/controll.html')
        # file_list = ([(name.split('/')[-1]) for name in file.GetFileList('../u-phi')])
        # lcopausb = lcopa_usb.LcopaUsb()
        # usb_id=lcopausb.get_usb_list()
        # #print file_list
        # return hello("sss",file_list,usb_id)
    def POST(self):
        data = web.input()
        respon_json={"respone_code":200,"msg":""}
        web.header('content-type','text/json')

        try:
            lcopausb = lcopa_usb.LcopaUsb()
            lcopausb.open(int(data['usb_id'],16))
        except Exception,e:
            print "error",e
            respon_json["msg"] = "usb error"
            respon_json["respone_code"] = 100
            return simplejson.dumps(respon_json)
        try:
            mu_phi = load_uphi_data.u_phi("../u-phi/"+data.file_name)
            # u_phi.load_uphi("../u-phi/"+data.file_name)
        except Exception,e:
            print "error",e
            respon_json["msg"] = "open uphi error"
            respon_json["respone_code"] = 100
            return simplejson.dumps(respon_json)
        print "mu_phi",mu_phi.toString()
        try:
            lcopa = calculate_codev.lcopa_vol(mu_phi)
            btyes = lcopa.calculate_voltage2_pi(float(data.angle1),float(data.angle2),float(data.n_pi))
            # print "btyes",btyes
        except Exception,e:
            print "error",e
            respon_json["msg"] = "u-phi file is  error"
            respon_json["respone_code"] = 100
            return simplejson.dumps(respon_json)
        try:
            lcopausb.send_byte(btyes)
        except Exception,e:
            print "error",e
            respon_json["msg"] = "send usb data error"
            respon_json["respone_code"] = 100
            return simplejson.dumps(respon_json)
        #lcopausb.close()
        print "data",data
        return simplejson.dumps(respon_json)
class upload_uphi:
    def GET(self):
        upload = web.template.frender('./templates/upload_uphi.html')
        file_list = ([(name.split('/')[-1]) for name in file.GetFileList('./u-phi')])
        #print file_list
        return upload("sss",file_list)
    def POST(self):
        x = web.input(upload_file={})
        filedir = '../u-phi' # change this to the directory you want to store the file in.
        if 'upload_file' in x: # to check if the file-object is created
            filepath=x.upload_file.filename.replace('\\','/') # replaces the windows-style slashes with linux ones.
            filename=filepath.split('/')[-1] # splits the and chooses the last part (the filename with extension)
            fout = open(filedir +'/'+ filename,'w') # creates the file where the uploaded file should be stored
            fout.write(x.upload_file.file.read()) # writes the uploaded file to the newly created file.
            fout.close() # closes the file, upload complete.
        raise web.seeother('/upload')
if __name__ == "__main__":
    udp_server.UdpServer()
    tcp_server.TcpServer()
    app.run()


#app.run()